<template>
	<transition name="fade">
		<div class="push-pin" v-show="inLimit" :style="style">
			<slot />
		</div>
	</transition>
</template>

<script>
import { coordinate } from "@/components/Cesium/utils";
export default {
	name: "PushPin",
	props: {
		limits: {
			default: () => {
				return {
					left: 100,
					top: 100,
					right: 100,
					bottom: 100,
				};
			},
		},
		position: {
			default: () => {
				return {
					lng: 0,
					lat: 0,
					height: 0,
				};
			},
		},
	},
	data() {
		return {
			positionX: 0,
			positionY: 0,
		};
	},
	mounted() {
		this.viewer = this.$parent.viewer;
		this.eventBus = this.$parent.eventBus;
		this.registerEvents();
	},
	beforeDestroy() {
		this.unregisterEvents();
	},
	computed: {
		style() {
			return {
				transform: `translateX(${this.positionX}px) translateY(${this.positionY}px)`,
			};
		},
		inLimit() {
			if (!this?.$parent?.$parent.$el) return false;
			const { left, top, right, bottom } = this.limits;
			const { width, height } = this?.$parent?.$parent.$el.getBoundingClientRect();
			const { positionX, positionY } = this;
			return !(left > positionX || right + positionX > width || positionY < top || positionY + bottom > height);
		},
	},
	methods: {
		registerEvents() {
			if (!this.eventBus) return;
			this.eventBus.on("scene-pre-render", this.handleCamera);
			this.unregisterEvents = () => {
				this.eventBus.off("scene-pre-render", this.handleCamera);
			};
		},
		handleCamera() {
			try {
				coordinate.lngLatValid(this.position.lng, this.position.lat);
				const { scene } = this.viewer;
				let { x, y } = scene.cartesianToCanvasCoordinates(coordinate.lngLatToCartesian3(this.position));
				this.positionX = x ?? 0;
				this.positionY = y ?? 0;
			} catch (e) {
				return;
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.push-pin {
	position: absolute;
	z-index: 10;
	width: 0px;
	height: 0px;
}
</style>
